package cn.pegasus.teamwork.pegasus.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.iyizhan.teamwork.base.service.impl.BaseServiceImpl;
import cn.iyizhan.teamwork.base.util.PageHelper;
import cn.iyizhan.teamwork.base.util.PageObject;
import cn.pegasus.teamwork.pegasus.entity.BussRechargeConfig;
import cn.pegasus.teamwork.pegasus.entity.BussUserConsumorder;
import cn.pegasus.teamwork.pegasus.mapper.BussRechargeConfigMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussUserConsumorderMapper;
import cn.pegasus.teamwork.pegasus.service.BussServicePageageService;
import cn.pegasus.teamwork.pegasus.service.BussServiceProjectService;
import cn.pegasus.teamwork.pegasus.service.BussUserConsumorderService;
import cn.pegasus.teamwork.pegasus.service.BussUserIntegraltotalService;
import cn.pegasus.teamwork.pegasus.service.BussUserOrderService;
import cn.pegasus.teamwork.sysconfig.service.SysConfigMessageService;
import cn.pegasus.teamwork.util.DateCompareUtil;
import cn.pegasus.teamwork.util.SnowflakeIdWorker;
import cn.pegasus.teamwork.vo.WXOrderVO;
import cn.pegasus.teamwork.weixinpay.Constant;
import cn.pegasus.teamwork.weixinpay.service.PayService;

/**
 * @author ryan.bian
 * @version
 */
@Service("bussUserConsumorderService")
public class BussUserConsumorderServiceImpl extends BaseServiceImpl<BussUserConsumorder, BussUserConsumorderMapper>
		implements BussUserConsumorderService {
	// 注入当前dao对象
	@Autowired
	private BussUserConsumorderMapper bussUserConsumorderMapper;
	@Autowired
	private BussServicePageageService pageageService;
	@Autowired
	private BussServiceProjectService serviceProjectService;
	@Autowired
	private BussRechargeConfigMapper rechargeConfigMapper;

	@Autowired
	private BussUserIntegraltotalService integraltotalService;

	@Autowired
	private BussUserOrderService bussUserOrderService;
	
	@Autowired
	private SysConfigMessageService messageService;

	@Autowired
	private PayService payService;

	public BussUserConsumorderServiceImpl() {
		setMapperClass(BussUserConsumorderMapper.class, BussUserConsumorder.class);
	}

	@Override
	public PageObject<BussUserConsumorder> PageList(Map<String, Object> map) {
		int totalData = bussUserConsumorderMapper.getTotal(map);
		PageHelper pageHelper = new PageHelper(totalData, map);
		List<BussUserConsumorder> list = bussUserConsumorderMapper.findListByPage(pageHelper.getMap());
		if (null != list && list.size() > 0) {
			for (BussUserConsumorder o : list) {
				// 获取项目名称
				if (null != o.getObjectsId()) {
					String projectName = serviceProjectService.findProjectName(Long.valueOf(o.getObjectsId()));
					o.setProjectName(projectName);
				}
				// 获取套餐名称
				if (null != o.getPageageId()) {
					String pageageName = pageageService.getPageageName(Long.valueOf(o.getPageageId()));
					o.setPageageName(pageageName);
				}
			}
		}
		PageObject<BussUserConsumorder> pageObject = pageHelper.getPageObject();
		pageObject.setDataList(list);
		return pageObject;
	}

	@Override
	public BussUserConsumorder findConsumInfo(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		BussUserConsumorder order = bussUserConsumorderMapper.findListByPage(map).get(0);
		// 获取项目名称
		if (null != order.getObjectsId()) {
			String projectName = serviceProjectService.findProjectName(Long.valueOf(order.getObjectsId()));
			order.setProjectName(projectName);
		}
		// 获取套餐名称
		if (null != order.getPageageId()) {
			String pageageName = pageageService.getPageageName(Long.valueOf(order.getPageageId()));
			order.setPageageName(pageageName);
		}
		return order;
	}

	/**
	 * 用户充值
	 */
	public Map<String, Object> createUserRechage(Map<String, Object> map, int retype, int orderType) {
		// 查询充值列表信息
		int orderBalance = 0;
		if (orderType == 1) {
			int id = Integer.valueOf(map.get("id").toString());
			BussRechargeConfig br = new BussRechargeConfig();
			br.setId(id);
			br = rechargeConfigMapper.selectSingle(br);
			if (br != null) {
				orderBalance = br.getRechargeMoney().intValue();
				map.put("orderBalance", br.getRechargeMoney());

				map.put("giveBalance", br.getGiveMoney());
			} else {

			}
		} else if (orderType == 2) {

			if (map.get("orderBalance") != null) {
				orderBalance = Integer.valueOf(map.get("orderBalance").toString());
			}
		}
		// 创建本地订单
		String orderNo = createConsumOrderVo(map, retype, orderType);
		if (!StringUtils.isEmpty(orderNo)) {
			// 用户同意授权，获得的code
			String code = map.get("openid").toString();

			// 调用统一下单service
			WXOrderVO VO = new WXOrderVO();
			VO.setBody("凤凰洗车-会员充值");
			VO.setOpenid(code);
			VO.setOrderNo(orderNo);
			VO.setNotityUrl(Constant.RENOTIFY_URL);
			VO.setOrderBalance(orderBalance);
			Map<String, Object> signMap = payService.unifiedOrder(VO);

			if (signMap != null) {
				// 修改订单支付单
				BussUserConsumorder buc = new BussUserConsumorder();
				buc.setOrderNo(orderNo);
				buc = bussUserConsumorderMapper.selectSingle(buc);
				if (buc != null) {
					buc.setServicesNo(signMap.get("package").toString());
					bussUserConsumorderMapper.updateByEntity(buc);
					return signMap;
				}
			}
		} else {
			return null;
		}

		// 通知

		return null;
	}

	/**
	 * 用户充值-APP
	 */
	public Map<String, Object> createUserRechageForApp(Map<String, Object> map, int retype, int orderType) {
		// 查询充值列表信息
		int orderBalance = 0;
		if (orderType == 1) {
			int id = Integer.valueOf(map.get("id").toString());
			BussRechargeConfig br = new BussRechargeConfig();
			br.setId(id);
			br = rechargeConfigMapper.selectSingle(br);
			if (br != null) {
				orderBalance = br.getRechargeMoney().intValue();
				map.put("orderBalance", br.getRechargeMoney());

				map.put("giveBalance", br.getGiveMoney());
			} else {

			}
		} else if (orderType == 2) {

			if (map.get("orderBalance") != null) {
				orderBalance = Integer.valueOf(map.get("orderBalance").toString());
			}
		}
		// 创建本地订单
		String orderNo = createConsumOrderVo(map, retype, orderType);
		if (!StringUtils.isEmpty(orderNo)) {
			// 调用统一下单service
			WXOrderVO VO = new WXOrderVO();
			VO.setBody("凤凰洗车-会员充值");
			VO.setOrderNo(orderNo);
			VO.setNotityUrl(Constant.RENOTIFY_URL);
			VO.setOrderBalance(orderBalance);
			Map<String, Object> signMap = payService.unifiedOrderForApp(VO);

			if (signMap != null) {
				// 修改订单支付单
				BussUserConsumorder buc = new BussUserConsumorder();
				buc.setOrderNo(orderNo);
				buc = bussUserConsumorderMapper.selectSingle(buc);
				if (buc != null) {
					buc.setServicesNo(signMap.get("package").toString());
					bussUserConsumorderMapper.updateByEntity(buc);
					return signMap;
				}
			}
		} else {
			return null;
		}

		// 通知

		return null;
	}

	/**
	 * 添加用户消费订单表信息
	 * 
	 * @param orderVo
	 */
	public String createConsumOrderVo(Map<String, Object> map, int retype, int orderType) {
		try {
			String orderNo = String.valueOf(new SnowflakeIdWorker().nextId());
			BussUserConsumorder buc = new BussUserConsumorder();

			buc.setUserId(Long.valueOf(map.get("userId").toString()));
			buc.setOrderNo(String.valueOf(new SnowflakeIdWorker().nextId()));
			// 订单状态（1-充值；2-购买套餐；3-提现）
			buc.setOrderType(orderType);
			if (map.get("desc") != null) {
				buc.setOrderDesc(map.get("desc").toString());
			}

			buc.setServicesNo(""); // 服务商返回订单
			if (map.get("objectsId") != null) {
				buc.setObjectsId(map.get("objectsId").toString()); // 对应
																	// order_type
				buc.setPageageId(map.get("objectsId").toString()); // 对应sys_service_pageage的ID
			}
			// 的ID（项目或者套餐）
			buc.setOrderBalance(Long.valueOf(map.get("orderBalance").toString())); // 订单金额
			if (map.get("giveBalance") != null) {
				buc.setGiveBalance(Long.valueOf(map.get("giveBalance").toString()));
			}
			buc.setAvailableCount(1); // 可使用次数（针对购买套餐情况）
			buc.setUsedCount(0);// 已使用次数（针对购买套餐情况）',
			buc.setEffectiveTime("");// 有效时间（针对购买套餐情况）',
			buc.setRechargeType(retype); // 充值方式（1-微信支付；2-余额支付）
			buc.setTradeType(1); // 交易类型(1-公众号 2-APP;)',
			buc.setOrderStatus(1);// 订单状态（1-未支付；2-已支付；3-失败；）',

			buc.setFinishedStatus(1);// 订单完成状态（1-未完成；2-已完成；3-已失败；）',
			buc.setCreateTime(DateCompareUtil.getNowDate());// 订单创建时间',
			buc.setCreateUserId(Long.valueOf(map.get("userId").toString()));// 创建用户id',

			bussUserConsumorderMapper.insertByEntity(buc);
			return orderNo;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 用户充值订单回调接口
	 * 
	 * @param id
	 * @param map
	 * @return
	 */
	public boolean modifyRechargeOrder(String transaction_id, String orderBalance, String orderNo) {
		// 1. 用户充值
		BussUserConsumorder buc = new BussUserConsumorder();
		buc.setOrderNo(orderNo);
		BussUserConsumorder cvo = bussUserConsumorderMapper.selectSingle(buc);
		if (cvo.getServicesNo() != null && orderBalance.equals(cvo.getOrderBalance().toString())) {

			// if (!StringUtils.isEmpty(cvo.getServicesNo())){
			cvo.setOrderStatus(2);
			cvo.setFinishedStatus(2);
			cvo.setServicesNo(transaction_id);
			// 2. 对于用户充值后，对资金进行补充
			bussUserConsumorderMapper.updateByEntity(cvo);

			// 处理用户资金
			bussUserOrderService.handleUserRechargeMoney(cvo);

			// 充值处理时 对用户积分的处理
			integraltotalService.handleUserIntegraltotal(cvo.getId(), Integer.valueOf(cvo.getUserId().toString()),
					Integer.valueOf(cvo.getOrderBalance().toString()) / 100);
			
			try {
				messageService.addMessage(1,"2", "充值成功通知", "尊敬的 用户，您充值的  "+ Integer.valueOf(cvo.getOrderBalance().toString()) * 0.01 + " 元资金已经成功，请在个人中心进行查询，谢谢！",
						cvo.getUserId().toString());
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			return true;
		} else {
			return false;
		}

	}
}
